package com.lksy.web.dao.student;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;

import com.lksy.core.config.BaseDao;
import com.lksy.web.model.Student;

public class StudentDao extends BaseDao {

	private static StudentDao studentDao = new StudentDao();

	public static StudentDao getInstance() {
		return studentDao;
	}
	
	public boolean deleteStudent(Integer id) throws SQLException {
		QueryRunner run = new QueryRunner(dataSource);
		return run.update("delete from student where stid=?",id) > 1;
	}

	public Student findStudentBySearchId(Integer id) throws SQLException {
		QueryRunner run = new QueryRunner(dataSource);
		return run.query("select * from student where stid=?", new BeanHandler<Student>(Student.class),id);
	}
	
	public List<Student> list() throws SQLException {
		QueryRunner run = new QueryRunner(dataSource);
		return run.query("select * from student", new StudentHandler());
	}
	
	public boolean save(Student student) throws SQLException {
		QueryRunner run = new QueryRunner(dataSource);
		return run.update("insert into student(stname,stsex,stage,sttel,stdept,staddress) values(?,?,?,?,?,?)" , student.getStname(),
				student.getStsex(),student.getStage(),student.getSttel(),student.getStdept(),student.getStaddress()) > 1;
	}
	
	public boolean update(Student student) throws SQLException {
		QueryRunner run = new QueryRunner(dataSource);
		return run.update("update student set stname=?,stsex=?,stage=? where stid=?",student.getStname(),student.getStsex(),student.getStage(),student.getStid()) >= 1;
	}
	
	class StudentHandler implements ResultSetHandler<List<Student>> {
		
		// jdk1.7 新特性
		List<Student> student = new ArrayList<>();
		
		@Override
		public List<Student> handle(ResultSet rs) throws SQLException {
			while(rs.next()) {
				Student stud = new Student();
				stud.setStid(rs.getInt("stid"));
				stud.setStaddress(rs.getString("staddress"));
				stud.setStage(rs.getString("stage"));
				stud.setStdept(rs.getString("stdept"));
				stud.setStname(rs.getString("stname"));
				stud.setStsex(rs.getString("stsex"));
				stud.setSttel(rs.getString("sttel"));
				student.add(stud);
			}
			return student;
		}

		
	}
}
